package com.trendwise.software;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;

import org.apache.hadoop.io.WritableComparable;

public class DateWritable implements WritableComparable<DateWritable>{

	private final static SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
	
	private Date date;
	
	
	
	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public void write(DataOutput out) throws IOException {
		// TODO 자동 생성된 메소드 스텁
		out.writeLong(date.getTime());
	}

	public void readFields(DataInput in) throws IOException {
		// TODO 자동 생성된 메소드 스텁
		date=new Date(in.readLong());
	}

	public int compareTo(DateWritable o) {
		// TODO 자동 생성된 메소드 스텁
		Calendar cal=Calendar.getInstance();
        cal.setTime(date);
		int y1=cal.get(Calendar.YEAR),m1=cal.get(Calendar.MONTH);
		cal.setTime(o.getDate());
		int y2=cal.get(Calendar.YEAR),m2=cal.get(Calendar.MONTH);
		if(y1!=y2)return 1;
		if(m1!=m2)return 1;
		
		return 0;
	}
	
	public String toString(){
		return formatter.format(date);
	}

	private static String[] months=new String[]{"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};
	
	public static Date parse(String text){
		//16/Dec/2012:05:32:50 -0500
		Calendar cal=Calendar.getInstance();
		String[] temps=text.replace(':', '/').split("/");
		int day=Integer.parseInt(temps[0])
			,year=Integer.parseInt(temps[2])	
			,hour=Integer.parseInt(temps[3])
			
			;
		String mstr=temps[1].toLowerCase();
		
		for(int i=0;i<months.length;i++){
			if(mstr.equals(months[i])){
				cal.set(Calendar.MONTH, i);
				break;
			}
		}
		
		cal.set(Calendar.DATE, day);
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.HOUR, hour);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		
		return cal.getTime();
	}
}
